import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STData } from '@delon/abc/st';
import { SFSchema, SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TicketService } from '../../services/ticket.service';

@Component({
  selector: 'app-etc-invoiced-logs',
  templateUrl: './etc-invoiced-logs.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class ETCInvoicedLogsComponent extends BasicTableComponent {
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();

  constructor(public service: TicketService, private router: Router, public searchDrawerService: SearchDrawerService) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        exTime: {
          start: this.sf?.value.exTime?.[0] || '',
          end: this.sf?.value.exTime?.[1] || ''
        },
        invoiceMakeTime: {
          start: this.sf?.value.invoiceMakeTime?.[0] || '',
          end: this.sf?.value.invoiceMakeTime?.[1] || ''
        }
      });
    }
    return requestOptions;
  };
  afterRes = (data: any[], rawData?: any) => {
    return data.map(item => ({
      ...item,
      disabled: item.isCreationInpinv == '1'
    }));
  };
  routeTo(item: any) {
    return;
    this.router.navigate(['/ticket/invoice-requested-detail/1']);
  }

  exportList() {
    const params = { listSource: 1, pageSize: -1 };
    if (this.sf) {
      Object.assign(params, {
        ...this.sf?.value
      });
    }
    this.service.downloadFile(this.service.$api_export_invoice_logs_page, params);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        invoiceNum: {
          type: 'string',
          title: '发票号码',
          ui: {
            placeholder: '请输入',
            autocomplete: 'off'
          }
        },
        billCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        waybillCode: {
          type: 'string',
          title: '运单号',
          ui: {
            placeholder: '请输入'
          }
        },
        carNo: {
          type: 'string',
          title: '车牌号',
          ui: {
            placeholder: '请输入'
          }
        },
        exTime: {
          title: '交易时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        invoiceMakeTime: {
          title: '开票日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        sellerName: {
          type: 'string',
          title: '销售方',
          ui: {
            placeholder: '请输入'
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          },
          default: ''
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', type: 'checkbox', fixed: 'left', width: '50px', className: 'text-center' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '发票号码', index: 'invoiceNum', width: 100, type: 'link', click: item => this.routeTo(item) },
      { title: '发票代码', index: 'invoiceCode', width: 130 },
      { title: '订单号', index: 'billCode', width: 180 },
      { title: '运单号', index: 'waybillCode', width: 180 },
      { title: '入站口', index: 'enStationName', width: 100 },
      { title: '出站口', index: 'exStationName', width: 100 },
      { title: '司机', render: 'call3No', width: 140 },
      { title: '车牌号', index: 'carNo', width: 100 },
      // { title: '里程（km）', index: 'mileage', width: 120 },
      { title: '交易id', index: 'tradeId', width: 200 },
      {
        title: '交易金额（元）',
        index: 'fee',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fee }) }
      },
      { title: '税率', index: 'taxRate', width: 90, format: item => `${item.taxRate ? ((item.taxRate as number) * 100).toFixed(2) : 0}%` },
      {
        title: '金额（元）',
        index: 'invoiceAmount',
        width: 120,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.invoiceAmount }) }
      },
      {
        title: '税额（元）',
        index: 'totalTaxAmount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.totalTaxAmount }) }
      },
      {
        title: '价税合计（元）',
        index: 'totalAmount',
        width: 150,
        type: 'widget',
        className: 'text-right font-weight-bold',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.totalAmount }) }
      },
      { title: '进站时间', index: 'trafficStartTime', type: 'date', width: 150 },
      { title: '出站时间', index: 'trafficEndTime', type: 'date', width: 150 },
      { title: '交易时间', index: 'exTime', type: 'date', width: 150 },
      { title: '开票日期', index: 'invoiceMakeTime', type: 'date', width: 150 },
      { title: '销售方', index: 'sellerName', width: 150 },
      { title: '网络货运人', index: 'enterpriseInfoName', width: 220 },
      {
        title: '操作',
        width: '120px',
        fixed: 'right',
        className: 'text-center',
        buttons: [
          {
            text: '收票',
            acl: { ability: ['TICKET-ETC-INVOICE-LOGS-createFicoInpinv'] },
            click: item => {
              this.batchInvoice(item)
            }
          }
        ]
      }
    ];
  }
  get selectedRows() {
    return this.st?.list.filter(item => item.checked) || [];
  }
  batchInvoice(item?: { id: any; }) {
    let params: any[] = [];
    if(item) {
      params.push(item.id);
    } else {
      if (this.selectedRows.length <= 0) {
        this.service.msgSrv.error('请选择订单！');
        return;
      }
      this.selectedRows.forEach(item => {
        params.push(item.id);
      });
    }

    this.service.request(this.service.$api_createFicoInpinv, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('收票成功！')
        this.st.load(1);
      }
    });
  }
}
